package com.wjs.gulimall.gulimallmember.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.wjs.gulimall.gulimallmember.dao.MemberLevelDao;
import com.wjs.gulimall.gulimallmember.entity.MemberLevelEntity;
import com.wjs.gulimall.gulimallmember.exception.PhoneExsitException;
import com.wjs.gulimall.gulimallmember.exception.UsernameExsitException;
import com.wjs.gulimall.gulimallmember.vo.MemberLoginVo;
import com.wjs.gulimall.gulimallmember.vo.MemberRegistVo;
import com.wjs.gulimall.gulimallmember.vo.SocialUserVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallmember.dao.MemberDao;
import com.wjs.gulimall.gulimallmember.entity.MemberEntity;
import com.wjs.gulimall.gulimallmember.service.MemberService;

import javax.management.RuntimeErrorException;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();

        //获取默认会员等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());

        //检查手机号和用户名是否唯一，采用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setUsername(vo.getUserName());
        entity.setMobile(vo.getPhone());

        //密码要进行加密处理 MD5盐加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(passwordEncoder.encode(vo.getPassword()));
        entity.setNickname("用户"+ UUID.randomUUID().toString().substring(0,5));

        //设置其他信息

        this.baseMapper.insert(entity);

    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExsitException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExsitException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExsitException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExsitException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginacct()).or().eq("mobile", vo.getLoginacct()));
        if (entity != null) {
            //数据库密码
            String passwordDb = entity.getPassword();
            //用户输入的密码
            String password = vo.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //进行对比
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 社交登录功能
     *
     * @param vo
     * @return
     */
    @Override
    public MemberEntity Oauthlogin(SocialUserVo vo) throws Exception {
        String access_token = vo.getAccess_token();
        Map<String, String> map = new HashMap<>();
        map.put("access_token", access_token);
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), map);
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = JSON.parseObject(json);
        Integer id = jsonObject.getInteger("id");
        String name = jsonObject.getString("name");
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", id.toString()));
        //判断之前此社交用户是否登录过此网站
        if (entity != null) {
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(access_token);
            update.setUid(id.toString());
            update.setExpiresIn(vo.getExpires_in());
            this.baseMapper.updateById(entity);

            entity.setAccessToken(access_token);
            entity.setUid(id.toString());
            entity.setExpiresIn(vo.getExpires_in());
            return entity;
        } else {
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setUid(id.toString());
            memberEntity.setNickname(name);
            memberEntity.setAccessToken(access_token);
            memberEntity.setExpiresIn(vo.getExpires_in());
            this.baseMapper.insert(memberEntity);
            return entity;
        }
    }

}